package x.ovo.wechat.bot.plugin.push;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.dromara.hutool.json.JSONObject;
import org.dromara.hutool.json.JSONUtil;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

import org.dromara.hutool.core.text.StrUtil;

@Slf4j(topic = "FeiShuPushStrategy")
public class FeiShuPushStrategy implements PushStrategy {

    private static final String URL = "https://open.feishu.cn/open-apis/bot/v2/hook/";

    @Override
    public void push(Map<String, ?> config, OkHttpClient client, String flag, String content) {
        String accessToken = (String) config.get("access_token_feishu");
        if (StrUtil.isBlank(accessToken)) log.info("飞书推送：配置文件未配置“access_token_feishu”");
        else {
            String secret = (String) config.get("secret_feishu");
            JSONObject json = JSONUtil.ofObj()
                    .set("msg_type", "text")
                    .set("content", JSONUtil.ofObj().set("text", flag + ": " + content));
            Request request = new Request.Builder()
                    .url(URL + accessToken)
                    .post(RequestBody.create(json.toString(), MediaType.parse("application/json")))
                    .build();
            try (Response response = client.newCall(request).execute()) {
                JSONObject object = JSONUtil.parseObj(response.body().string());
                if (object.getInt("code") == 0 && object.getStr("msg").equals("success")) {
                    log.info("飞书推送成功");
                } else {
                    log.error("飞书推送失败");
                }
            } catch (IOException e) {
                log.error("飞书推送失败: {}", e.getMessage());
            }
        }
    }

    @SneakyThrows
    private String caclSignature(Long timestamp, String secret) {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
        return URLEncoder.encode(new String(Base64.getEncoder().encode(signData), StandardCharsets.UTF_8), StandardCharsets.UTF_8);
    }
}
